package com.kehao.leetcode.jzoffer;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/7/7 10:55
 */
public class JZSolution049 {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int result = 0;

    private void dfs(TreeNode node, LinkedList<Integer> stack){
        if(node==null) return;
        stack.addLast(node.val);
        if(node.left==null&&node.right==null){
            int value = getValue(stack);
            result+=value;
        }
        dfs(node.left,stack);
        dfs(node.right,stack);
        stack.removeLast();
    }

    private int getValue(List<Integer> list){
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum = sum*10+list.get(i);
        }
        return sum;
    }

    public int sumNumbers(TreeNode root) {
        result = 0;
        LinkedList<Integer> stack = new LinkedList<>();
        dfs(root,stack);
        return result;
    }
}
